# -*- coding: utf-8 -*-
"""
-------------------------------------------------------------------------------
File    : MqttReceive.py
Time    : 2023/11/9 13:58
author  : mojin
Email   : 397135766@qq.com
-------------------------------------------------------------------------------
"""


import paho.mqtt.client as mqtt
from common.logger import Logger
from common import qt_message as mgs
import time
import time
from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5 import QtWidgets

class MqttReceive(QThread):

    mqtt_receive_connect_status = pyqtSignal(dict)  # 用于更新进度条的信号

    def __init__(self,broker_address,broker_port,client_ID,name_mqtt,pwd_mqtt):
        super().__init__()
        # MQTT代理服务器的地址和端口号
        #self.topic = topic
        self.broker_address = broker_address  # 192.168.1.202:61616
        self.broker_port = int(broker_port)
        self.client_ID=client_ID
        self.name_mqtt=name_mqtt
        self.pwd_mqtt=pwd_mqtt

        self.receive_topic = None #接收消息主题
        self.receive_message_box=None  # 接收消息输入框
        self.connections_number_connect=1
        self.connections_number_status=1

    def mqtt_connect(self):

        # 创建MQTT客户端
        self.client = mqtt.Client(self.client_ID)

        self.client.on_connect = self.on_connect # 设置回调函数
        self.client.on_disconnect = self.on_disconnect # 设置回调函数
        #self.textEdit=''

        # # 订阅主题
        #self.client.subscribe('gnsstopic3')
        self.connect_status = False
        self.startup_status = True
        self.connection_error=False

        self.connected = False


        while not self.connected:
            try:
                # 连接到MQTT代理服务器
                try:

                    #self.name_mqtt,self.pwd_mqtt
                    if self.name_mqtt!='' and self.pwd_mqtt!='':
                        # 设置用户名和密码（如果需要的话）
                        self.client.username_pw_set(self.name_mqtt,self.pwd_mqtt)

                    self.client.connect(self.broker_address, self.broker_port)
                    self.connected = True
                    self.client.loop_start()  # 启动一个线程用于处理网络事件
                except Exception as e:
                    time.sleep(1)
                    self.connection_error=True
                    Logger.error(f'连接失败！！（{e}）')
                    dic_data={
                        "code":3
                    }
                    self.mqtt_receive_connect_status.emit(dic_data)  # 发送完成信号
                    break

                    # if not self.startup_status:
                    #     self.client.loop_stop()  # 停止网络事件处理线程
                    #     self.client.disconnect()  # 断开连接
                    #     Logger.info('mqtt 放弃连接……')
                    #     self.mqtt_receive_connect_status.emit(1)  # 发送完成信号
                    #     break
            except ConnectionRefusedError:
                # print("Connection refused, retrying in 2 seconds...")
                Logger.info(f'mqtt 正在尝试连接中 [{self.connections_number_connect}]……')
                self.connections_number_connect = self.connections_number_connect + 1

            time.sleep(1)

    def on_connect(self,client, userdata, flags, rc):

        if rc == 0:
            print("Connected to broker")
            self.connect_status = True
            #self.startup_status = True
            Logger.info('mqtt 连接成功……')
            dic_data = {
                "code": 0,
                'receive_topic':  None #接收消息主题
            }
            #self.subscribe_receive_msg()
            self.mqtt_receive_connect_status.emit(dic_data)  # 发送完成信号
            self.connections_number_connect = 1
            self.connections_number_status= 1


        else:
            print("Connection failed")
            self.connect_status = False
            self.connection_error = True
            dic_data = {
                "code": 2
            }
            self.mqtt_receive_connect_status.emit(dic_data)  # 发送完成信号


    def on_disconnect(self,client, userdata, rc):

        if rc != 0:
            print("Unexpected disconnection")
            dic_data = {
                "code": 2
            }

            self.connect_status = False
            self.mqtt_receive_connect_status.emit(dic_data)  # 发送完成信号


    def on_message(self,client, userdata, msg):
        #Logger.info("Received message: " + str(msg.payload.decode("latin-1")))
        #self.mqtt_receive_msg.emit(self.kwargs)  # 发送完成信号
        mgs.log(self.receive_message_box,str(msg.payload.decode("latin-1")),mmodule=msg.topic)

        Logger.info("接收消息：[{}] {}".format(msg.topic, msg.payload.decode('latin-1')))

    def seed_info(self,topic, message):
        self.client.publish(topic, message)  # 发布消息
        Logger.info(f"发送消息:[{topic}] {message}")
        #Logger.info('发送完成……')

    def subscribe_receive_msg(self): #订阅接收消息主题
        if self.receive_topic!=None:
            self.client.subscribe(self.receive_topic)  # 订阅主题
            self.client.on_message = self.on_message  # 设置回调函数



    def unsubscribe_receive_msg(self,topic):
        self.client.unsubscribe(topic)  # 订取消订阅
        # self.client.on_message = self.on_message
        # self.textEdit=textEdit




    def run(self):
        self.mqtt_connect()



        while True:
            if not self.connection_error:
                if self.connect_status:
                    if  not self.startup_status:
                        self.client.loop_stop()  # 停止网络事件处理线程
                        self.client.disconnect() # 断开连接

                        Logger.info('mqtt 断开成功……')
                        dic_data = {
                            "code": 1
                        }

                        self.mqtt_receive_connect_status.emit(dic_data)  # 发送完成信号
                        break

                else:
                    if  not self.startup_status:
                        self.client.loop_stop()  # 停止网络事件处理线程
                        self.client.disconnect() # 断开连接

                        Logger.info('mqtt 断开成功……')
                        dic_data = {
                            "code": 1
                        }
                        self.mqtt_receive_connect_status.emit(dic_data)  # 发送完成信号
                        break


                    Logger.info(f'mqtt 等待连接中 [{self.connections_number_status}]……')
                    dic_data = {
                        "code": 4,
                        'msg':f'连接中[{self.connections_number_status}]',
                        'number':self.connections_number_status,
                    }
                    self.mqtt_receive_connect_status.emit(dic_data)  # 发送完成信号


                    self.connections_number_status = self.connections_number_status + 1

                time.sleep(1)



